import axios from 'axios'
import { ElMessage } from 'element-plus'

let _axios = axios.create({
    baseURL: 'http://47.92.174.180:8080',
    // baseURL: 'http://localhost:8080',
})

//请求拦截器
_axios.interceptors.request.use(
    async function (config) {
        //请求正常下，在每一个请求的请求头里添加Jwt的Token
        // let authorization = localStorage.getItem('Authorization') || sessionStorage.getItem('Authorization')
        let authorization = localStorage.getItem('Authorization')
        if (authorization) {
            let token = JSON.parse(authorization)
            if (token.expireTime < Date.now()) {
                localStorage.removeItem('Authorization')
                // sessionStorage.removeItem('Authorization')
                sessionStorage.removeItem('web')
                ElMessage({
                    showClose: true,
                    message: "登录状态已过期,请重新登录",
                    type: 'warning',
                    appendTo: ".common-layout",
                })
                router.push("/login")
            }
            config.headers = {
                ...config.headers,
                Authorization: 'Bearer ' + token.Authorization
            }
        }
        return config
    },
    //请求异常时抛出异常
    function (error) {
        return Promise.reject(error)
    }
)

//响应拦截器
_axios.interceptors.response.use(
    //响应正常时
    function (response) {
        if (response.data.code === 400) {
            ElMessage({
                showClose: true,
                message: '请求参数不正确',
                type: 'error',
                appendTo: ".appHeader",
            })
        } else if (response.data.code === 403) {
            ElMessage({
                showClose: true,
                message: response.data.message,
                type: 'warning',
                appendTo: ".appHeader",
            })
        } else if (response.data.code === 404) {
            ElMessage({
                showClose: true,
                message: '请求的资源不存在',
                type: 'error',
                appendTo: ".appHeader",
            })
        }
        return response
    },
)
export default _axios